package com.mission.listview

import android.app.Activity
import android.view.LayoutInflater
import android.view.View
import android.view.ViewGroup
import android.widget.ArrayAdapter
import android.widget.ImageView
import android.widget.TextView

/**
 * Created by KevenTao on 1/5/21.
 */
class FruitAdapter(activity: Activity, val resourceId: Int, data: List<Fruit>) :
    ArrayAdapter<Fruit>(activity, resourceId, data) {

    override fun getView(position: Int, convertView: View?, parent: ViewGroup): View {
        val view: View
        val mViewHolder: ViewHolder
        if (convertView == null) {
            view = LayoutInflater.from(context).inflate(resourceId, parent, false)
            val fruitImage: ImageView = view.findViewById(R.id.fruit_image)
            val fruitName: TextView = view.findViewById(R.id.fruit_name)
            mViewHolder = ViewHolder(fruitImage, fruitName)
            view.tag = mViewHolder
        } else {
            view = convertView
            mViewHolder = view.tag as ViewHolder
        }

        val fruit = getItem(position)
        fruit?.let {
            mViewHolder.fruitImage.setImageResource(it.picId)
            mViewHolder.fruitName.setText(it.name)
        }
        return view
    }

    inner class ViewHolder(val fruitImage: ImageView, val fruitName: TextView)
}